If you are working as Node js Developer or want to start a career as Node js Developer then you should know the difference between callback and promise. In this article, I will explain to you the basic difference between callback and promise in an easy way.
In Javascript, you have two main methods to handle asynchronous tasks – 1. Callback and 2. Promise. For a very long time, synchronizing asynchronous tasks in JavaScript was a serious issue. This difficulty affects back-end developers using Node.js as well as front-end developers using any JavaScript framework. Asynchronous programming is part of our daily work, but the challenge is often taken lightly and not considered at the right time.
Now we will learn the basic definition of callback and promise with an example:
Callback:
A Callback is a function that we call inside another function. A callback may or may not performed asynchronously. Normally callback runs after the parent function completes its operation.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function calculate(x) { return x+2; } function display(y) { //execute y return y(5); } console.log(display(calculate)); // Result: 7 |
Here calculate() is a function. We are passing it as a callback to function display(). Function display() may or may not execute it asynchronously. Here callback is executed asynchronously.
Promise:
A Promise is an object which takes a callback and executes it asynchronously. A promise is considered easier to use and to maintain than callbacks.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
var promise = new Promise(function(resolve, reject) { // do a thing, possibly async, then… if () { /* everything turned out fine */ resolve("Stuff worked!"); } else { reject(Error("It broke")); } }); promise.then(function(result) { console.log(result); // "Stuff worked!" }, function(err) { console.log(err); // Error: "It broke" }); |
As we can see, then() takes two arguments, one for success, one for failure (or fulfill and reject, in promises-speak).
A promise did not remove the use of callbacks, but it made the chaining of functions straightforward and simplified the code, making it much easier to read.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var promise = new Promise(function(resolve, reject) { if () { /* everything turned out fine */ resolve("Stuff worked!"); } else { reject(Error("It broke")); } }); promise.then(function(result) { console.log(result); // "Stuff worked!" }).catch(function(err) { console.log(err); // Error: "It broke") }); |
If you will compare the Promise code, it is much more readable then Callback function code.
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co